package com.rc.web.controller;

import com.rc.common.util.JsonUtil;
import com.rc.common.util.PositionUtil;
import com.rc.pojo.dto.search.SearchDTO;
import com.rc.pojo.po.SearchDoc;
import com.rc.web.service.HistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 活动表 控制层。
 *
 * @author sym
 * @since 2024-05-26
 */
@RestController
@RequestMapping("/search")
@Api(tags = "搜索")
@RequiredArgsConstructor
@Validated
public class SearchController {
    private final RestHighLevelClient restHighLevelClient;
    private final HistoryService historyService;
    private final RestTemplate restTemplate;

    @GetMapping
    @ApiOperation("关键字搜索")
    //TODO 封装service 封装elasticsearch repository
    public List<SearchDoc> search(@Validated SearchDTO dto) throws IOException {
        var request = new SearchRequest("items");

        var query = QueryBuilders.multiMatchQuery(dto.getKeyword(),
                "title",
                "description"
        );

        request.source().query(query);

        var search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        var searchHits =  search.getHits();

        var searchDocList = new ArrayList<SearchDoc>();
        searchHits.forEach(hit->{
            var source = hit.getSourceAsString();
            var searchDoc = JsonUtil.toObj(source, SearchDoc.class);
            var distance = PositionUtil.distance(searchDoc.getLng(), searchDoc.getLat(), dto.getLng(), dto.getLat());
            searchDoc.setDistance(distance);
            searchDocList.add(searchDoc);
        });

        return searchDocList;
    }

    @GetMapping("/like")
    @ApiOperation("猜你喜欢")
    public List<String> like(){
        return historyService.getLastSix();
    }

    @GetMapping(value = "/test",produces = "application/json; charset=UTF-8")
    public String test(@NotBlank @RequestParam String keyword){
        var url = "https://cn.bing.com/search?q=" + keyword.replace("?","")
                .replace("？","");

        var headers = new HttpHeaders();
        headers.set("Cookie","MUIDB=04572BEF4814644E033F3F9049A8650D");

        var html = restTemplate.postForObject(url, headers, String.class);
        var doc = Jsoup.parse(html);

        var result = doc.selectFirst("#b_results");
        var select = result.select(".b_algo");

        var sb = new StringBuilder();
        select.forEach(item ->{
            Element element = item.selectFirst("p");

            if (element != null){
                String text = element.text()
                        .replace("/网页.*年.*月.*日/g", "")
                        .replace("·", "")
                        .replace("网页", "");

                sb.append(text);
            }
        });

        return sb.toString();
    }
}
